import type { MenuDataItem, Settings as LayoutSettings } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
import type { RequestConfig, RunTimeLayoutConfig } from 'umi';
import type { RequestOptionsInit } from 'umi-request';
import { history, Link } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import { LinkOutlined } from '@ant-design/icons';
import { fixMenuItemIcons } from './utils/fixMenuItemIcon';
import errorHandler from './utils/errorHandler';
import { localRead } from './utils';
import { isDev, loginPath } from './utils/constants';
import { queryDynamicRoutesUsingGET } from './services/swagger/menu';
import { queryCurrentUserUsingGET } from './services/swagger/user';
import defaultSettings from '../config/defaultSettings';
import HeaderContent from './components/HeaderContent';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  collapsed?: boolean;
  menuData?: MenuDataItem[];
  currentUser?: API.UserProfileVo;
  fetchMenuData?: () => Promise<API.RouteVo[] | undefined>;
  fetchUserInfo?: () => Promise<API.UserProfileVo | undefined>;
}> {


  // 获取动态菜单
  const fetchMenuData = async () => {
    try {
      const response = await queryDynamicRoutesUsingGET();
      return response.data;
    } catch (error) {
      console.log('获取动态菜单异常', error);
      history.push(loginPath);
    }
    return undefined;
  };

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const response = await queryCurrentUserUsingGET();
      return response.data;
    } catch (error) {
      console.log('获取用户信息异常', error);
      history.push(loginPath);
    }
    return undefined;
  };

  // 如果是登录页面，不执行
  if (history.location.pathname !== loginPath) {
    // 从服务器加载菜单,用户信息
    const [menuData, currentUser] = await Promise.all([fetchMenuData(), fetchUserInfo()]);
    return {
      fetchMenuData,
      fetchUserInfo,
      menuData,
      currentUser,
      settings: defaultSettings,
    };
  }
  return {
    fetchMenuData,
    fetchUserInfo,
    settings: defaultSettings,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {

  const onCollapse = (collapsed: boolean) => {
    setInitialState({
      ...initialState,
      collapsed
    }).then()
  }


  // 处理菜单数据
  const menuDataRender = () => {
    return fixMenuItemIcons(initialState?.menuData || []);
  };

  return {
    // 去除系统自带 collapsedButton
    collapsedButtonRender: false,
    // 指定配置collapsed
    collapsed: initialState?.collapsed,
    headerContentRender: () => <HeaderContent onCollapse={onCollapse} />,
    rightContentRender: () => <RightContent />,
    breadcrumbRender: (routers = []) => [
      {
        path: '/',
        breadcrumbName: '主页',
      },
      ...routers,
    ],
    disableContentMargin: false,
    // 系统水印
    // waterMarkProps: {
    //   content: initialState?.currentUser?.nickname,
    // },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    links: isDev
      ? [
        <Link to="/umi/plugin/openapi" target="_blank">
          <LinkOutlined />
          <span>OpenAPI 文档</span>
        </Link>
      ]
      : [],
    menuHeaderRender: undefined,
    // 从服务器动态获取菜单
    menuDataRender: () => menuDataRender(),
    // 自定义渲染菜单项
    // menuItemRender: (menuItem, defaultDom) => {
    //   console.log(menuItem, defaultDom)
    //   if (menuItem.isUrl || !menuItem.path) {
    //     return defaultDom
    //   }
    //   // 支持二级菜单显示ICON
    //   return (
    //     <Link to={menuItem.path}>
    //       {menuItem.parentId !== '0' && menuItem.icon}{defaultDom}
    //     </Link>
    //   )
    // },
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    // childrenRender: (children) => {
    //   if (initialState.loading) return <PageLoading />;
    //   return children;
    // },
    ...initialState?.settings,
  };
}

// request 请求拦截器
const authHeaderInterceptor = (url: string, options: RequestOptionsInit) => {
  const tokenInfo = localRead('UserToken');
  if (tokenInfo) {
    const { tokenHead, token } = tokenInfo;
    const authHeader = { Authorization: tokenHead + token };
    return {
      url: `${url}`,
      options: { ...options, interceptors: true, headers: authHeader },
    };
  }
  return {
    url: `${url}`,
    options: { ...options, interceptors: true },
  };
};

const baseUrl = isDev ? '' : '';

/**
 * 网络请求配置
 * @see https://beta-pro.ant.design/docs/request-cn
 */
export const request: RequestConfig = {
  // 超时时间
  timeout: 5000,
  prefix: `${baseUrl}`,
  errorHandler,
  // errorConfig: {
  //   adaptor: (res) => {
  //     return {
  //       success: res.success,
  //       errorCode: res.code,
  //       errorMessage: res.message,
  //     };
  //   },
  // },
  // 新增自动添加AccessToken的请求前拦截器
  requestInterceptors: [authHeaderInterceptor],
  // responseInterceptors: [appResponseInterceptors],
};